//左侧导航
import React, { useEffect, useState } from "react";
import { Layout, Menu } from "antd";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import axios from "axios";
import "./index.css";

const { Sider } = Layout;
const { SubMenu } = Menu;
//数据请求渲染
const SideMenu = (props) => {
  const [menu, setmenu] = useState([]);
  useEffect(() => {
    axios.get("/rights?_embed=children").then((res) => {
      setmenu(res.data);
    });
  }, []);
  //取出用户列表中的数据
  const {
    role: { rights },
  } = JSON.parse(localStorage.getItem("token"));
  //判断菜单是否可以下拉
  const checkPagePermission = (item) => {
    return item.pagepermisson && rights.includes(item.key);
  };
  //列表渲染
  const renderMenu = (menuList) => {
    return menuList.map((item) => {
      if (item.children?.length > 0 && checkPagePermission(item)) {
        return (
          <SubMenu key={item.key} icon={item.icon} title={item.title}>
            {renderMenu(item.children)}
          </SubMenu>
        );
      }
      return (
        checkPagePermission(item) && (
          <Menu.Item
            key={item.key}
            icon={item.icon}
            onClick={() => {
              props.history.push(item.key);
            }}
          >
            {item.title}
          </Menu.Item>
        )
      );
    });
  };
  //取出路由判断哪个高亮
  const selectKeys = [props.location.pathname];
  //截取出导航根目录决定哪个是否展开
  const openKeys = ["/" + props.location.pathname.split("/")[1]];
  return (
    <Sider trigger={null} collapsible collapsed={props.isCollapsed}>
      <div style={{ display: "flex", height: "100%", flexDirection: "column" }}>
        <div className="logo"> 新闻发布系统 </div>
        <div style={{ flex: 1, overflow: "auto" }}>
          <Menu
            theme="dark"
            mode="inline"
            selectedKeys={selectKeys}
            defaultOpenKeys={openKeys}
          >
            {renderMenu(menu)}
          </Menu>
        </div>
      </div>
    </Sider>
  );
};
const mapStateToProps = (state) => {
  const {
    CollapsedReducer: { isCollapsed },
  } = state;
  return {
    isCollapsed,
  };
};
export default connect(mapStateToProps)(withRouter(SideMenu));
